package cube.io.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网页读取器
 * 
 * @author abiao
 */
public abstract class WebReader {

    /**
     * BufferedReader
     */
    private BufferedReader br;

    /**
     * 停止读取
     */
    private boolean stop;

    /**
     * 网页读取器
     */
    public WebReader(String url, String charset) {
        initWebReader(url, charset);
    }

    /**
     * 初始化网页读取器
     */
    private void initWebReader(String url, String charset) {
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, charset));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始读取行
     */
    public void start() {
        try {
            if (br != null) {
                String line;
                while ((line = br.readLine()) != null) {
                    if (stop) {
                        break;
                    }
                    readLine(line);
                }
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止读取
     */
    public void stop() {
        this.stop = true;
    }

    /**
     * 读取一行数据
     */
    public abstract void readLine(String line);
}
